//
//  UserConfigs.swift
//  SitPosition
//
//  Created by apple on 2019/2/7.
//  Copyright © 2019 apple. All rights reserved.
//

import Foundation


/**
 * 用户的学习配置网络返回模型
 */
struct UserConfigs : Codable {
    
    // 默认值
    public static let defaultAngle: Float = 1.0
    public static let defaultStudyTime: Int = 30*60
    public static let defaultBlackScreenTime: Int = 2*60
    public static let defaultAlarmTime: Int = 3
    public static let defaultDepartureTime: Float = 3*60
    
    // 设置当前用户的配置
    static var current: UserConfigs? = nil {
        didSet {
            dbgPrint("current userConfigs changed")
        }
    }
    
    let id: String                  // 用户id
    var angleValue: Float?          // 姿态角度设置，0 < angleValue < 2，越小越灵敏，默认值建议1.1
    var studyTime: Int?             // 连续学习时长，单位秒，默认30分钟
    var blackScreenTime: Int?       // 自动黑屏时间，单位秒，默认2分钟
    var alarmTime: Int?             // 错误姿态的报警的间隔时间，单位秒，默认3秒
    var departureTime: Int?         // 离开课桌多久自动退出应用，单位秒，默认3分钟
    var ttsSound: String?           // TTS发音
    
    // 可以使用 CodingKeys 改变编码属性的名称
    enum CodingKeys : String, CodingKey {
        case id
        case angleValue
        case studyTime
        case blackScreenTime
        case alarmTime
        case departureTime
        case ttsSound
    }
}


extension UserConfigs {
    
    // 从本地存储加载
    public static func load(_ userId: String) -> UserConfigs? {
        do {
            let path = try Paths.userConfigsPath(userId)
            guard FileManager.default.fileExists(atPath: path) else {
                return nil
            }
            let url: URL = URL(fileURLWithPath: path)
            let data: Data = try Data(contentsOf: url)
            let decoder: JSONDecoder = JSONDecoder()
            return try decoder.decode(UserConfigs.self, from: data)
        } catch {
            return nil
        }
    }
    
    // 同步到本地存储
    public func save(_ needCommit: Bool, completion: ((Error?) -> Void)?) {
        do {
            let path = try Paths.userConfigsPath(self.id)
            let encoder: JSONEncoder = JSONEncoder()
            let data: Data = try encoder.encode(self)
            let url: URL = URL(fileURLWithPath: path)
            try data.write(to: url)
        } catch {
            dbgPrint("failed to save userConfigs: \(self.id)")
        }
        
        guard needCommit else { return }
        NetworkClient.instance.updateUserConfigs(userId: self.id, userConfigs: self, success: { (data) in
            completion?(nil)
        }, failure: completion)
    }
    
    // 拉取并刷新当前用户的配置
    public static func refreshCurrentUserConfigs(_ completion: @escaping (Error?) -> Void) {
        guard UserManager.manager.isLogin(),
            let user_ = UserManager.manager.user,
            let userId = user_.id else {
                return
        }
        if let userConfigs = UserConfigs.load(userId) {
            UserConfigs.current = userConfigs
        }
        NetworkClient.instance.queryUserConfigs(userId: userId, success: { (data) in
            // 检查参数
            guard let data_ = data else {
                dbgPrint("unexpected server response.")
                completion(SPError.unexpectedServerResponse)
                return
            }
            
            // 注册成功
            do {
                let decoder: JSONDecoder = JSONDecoder()
                let userConfigs = try decoder.decode(UserConfigs.self, from: data_)
                UserConfigs.current = userConfigs
                userConfigs.save(false, completion: nil)
                completion(nil)
            } catch {
                dbgPrint("failed to decode userConfigs model: \(error)")
                completion(error)
            }
        }, failure: { (error) in
            dbgPrint("failed to fetch userConfigs of the current user: \(String(describing: error))")
            completion(error)
        })
    }
    
}
